package com.test.service.Impl;

import com.test.Aspect.BusinessException;
import com.test.dao.DishMapper;
import com.test.domain.Dish;
import com.test.domain.DishExample;
import com.test.enums.Page;
import com.test.enums.Replay;
import com.test.enums.ReplayCode;
import com.test.service.DishService;
import com.test.utils.ReplayUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * DishServiceImpl
 *
 * @author HY
 * 2021/05/24 8:44
 **/


@Service
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Override
    public Replay insert(Dish dish) {

        if (dish.getName() == null || dish.getName().equals("")){
            throw new BusinessException(ReplayCode.REQUIREDNULL_ERR);
        }

        int rs = dishMapper.insert(dish);

        if (rs < 1 ){
            throw new BusinessException(ReplayCode.DO_ERR);
        }
        return ReplayUtil.success();
    }

    @Override
    public Replay del(int id) {
        // TODO 删除待完成
        return ReplayUtil.success();
    }

    @Override
    public Replay update(Dish dish) {

        if (dish.getId() == null || dish.getId().equals("")){
            throw new BusinessException(101,"必填参数不能为空");
        }

        DishExample dishExample = new DishExample();
        DishExample.Criteria criteria = dishExample.createCriteria();

        criteria.andIdEqualTo(dish.getId());

        int rs = dishMapper.updateByExampleSelective(dish, dishExample);

        if (rs < 1){
            throw new BusinessException(ReplayCode.DO_ERR);
        }

        return ReplayUtil.success();
    }

    @Override
    public Replay select(Dish dish, Page page) {

        if (page.isNull()){
            //抛出空值异常
            throw new BusinessException(ReplayCode.Page_NULL);
        }

        DishExample dishExample = new DishExample();
        DishExample.Criteria criteria = dishExample.createCriteria();

        //查询条件
        if (dish.getName() != null || !dish.getName().equals("")){
            criteria.andNameLike("%"+dish.getName()+"%");
        }

        List<Dish> dishes = dishMapper.selectByExample(dishExample);
        int count = (int) dishMapper.countByExample(dishExample);

        return ReplayUtil.success("查询成功", dishes, count);
    }

    @Override
    public Dish selectById(Dish dish) {
        Dish dish1 = dishMapper.selectDishById(dish);
        return dish1;
    }
}
